﻿uniform sampler2D tex;
uniform vec3 axis;
uniform vec3 eye;

const float K_d = 1.0;
const vec3 K_s = vec3(0.2, 0.2, 0.2);
const float shininess = 150.0;

const float rho_reflect = 0.9;
const float rho_transmit = 0.3;

varying vec4 pos;
varying float opacityFactor;

float vecSin(vec3 a, vec3 b) // a and b are normalized
{
	return length(a - dot(a, b) * b);
}

void main()
{
	vec4 color = texture2D( tex, gl_TexCoord[0].st );
	vec4 matSpec = gl_FrontMaterial.specular;
	vec4 lightSpec = gl_LightSource[0].specular;
	
	color[0] = 0.55;
	color[1] = 0.26;
	color[2] = 0.13;
	
	
	vec3 t = normalize( axis );
	
	vec3 l = vec3(normalize( gl_LightSource[0].position - pos ));
	
	float intensity = K_d * vecSin(t, l); // sin(t, l)
	
	vec3 diffuse = intensity * color.xyz;
	
	
	vec3 e = vec3(normalize( vec4( eye, 1 ) - pos ));
	
	float dotTL = dot( t, l );
	float dotTE = dot( t, e );
	//float sinTL = vecSin( t, l );
	//float sinTE = vecSin( t, e );
	float sinTL = sqrt( 1 - dotTL * dotTL );
	float sinTE = sqrt( 1 - dotTE * dotTE );
	
	vec3 specular = K_s * pow( dotTL * dotTE + sinTL * sinTE, shininess );
	
	
	vec3 crossTL = cross(t, l);
	vec3 crossTE = cross(t, e);
	float K_goldman = dot(crossTL, crossTE) / ( length(crossTL) * length(crossTE) );
	
	float f_dir = rho_reflect * (1 + K_goldman) / 2 + rho_transmit * (1 - K_goldman) / 2;
	
	
	color.xyz = f_dir * (diffuse + specular);
	
	color[3] = opacityFactor * color[3];
	
	gl_FragColor = color;
}